package register

import (
	"net/http"
	"time"

	"gitee.com/fanshuaiself/sidecar/util"
)

type HealthChecker interface {
	IsHealth() bool
}

type httpHealthChecker struct {
	host string 
	client *http.Client
}

func (c *httpHealthChecker) IsHealth() bool {
	rep, err := http.NewRequest("GET", c.host, nil)
	if err != nil {
		return false
	}

	resp, err := c.client.Do(rep)
	if err != nil {
		return false
	}
	if resp != nil && resp.Body != nil {
		resp.Body.Close()
	}

	return true
}

func newHttpChecker(config *util.Config) *httpHealthChecker {
	return &httpHealthChecker{
		host: config.Host,
		client: &http.Client {
			Timeout: 30 * time.Second,
			CheckRedirect: func(req *http.Request, via []*http.Request) error {
				return http.ErrUseLastResponse
			},
		},
	}
}